from flask import Flask, request, jsonify
import json

app = Flask(__name__)

# 使用绝对路径确保文件能找到
json_file_path = r"D:\PyCharm\PyCharmProject\接口造数据\air\generated_data.json"

with open(json_file_path, "r", encoding="utf-8") as f:
    flights_data = json.load(f)


@app.route("/check", methods=["GET"])
def check_flight():
    start = request.args.get("start")
    end = request.args.get("end")
    time_str = request.args.get("time")

    if not start or not end or not time_str:
        return jsonify({"code": 400, "msg": "缺少必要参数"}), 400

    try:
        time = int(time_str)
    except ValueError:
        return jsonify({"code": 400, "msg": "时间格式错误"}), 400

    matching_flights = []
    for item in flights_data:
        if (
            item.get("start") == start
            and item.get("end") == end
            and item.get("time") == time
            and item.get("available") == 1
        ):
            matching_flights.append({
                "code": 100,
                "available": 1,
                "price": item.get("price"),
                "start": item.get("start"),
                "end": item.get("end"),
                "time": item.get("time")
            })
    if len(matching_flights) > 0:
        return jsonify(matching_flights)
    else:
        return jsonify({
            "code": 200,
            "msg": "无该航段信息",
            "available": 0,
            "price": None
        })

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
